#include "selfmarketdialog.h"
#include "ui_selfmarketdialog.h"
#include<QMessageBox>
#include"ufxconfig.h"
#include"CtpInterface/ctpinterface.h"

extern CTPInterface* g_CTPInterface;

SelfMarketDialog::SelfMarketDialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::SelfMarketDialog)
{
    ui->setupUi(this);
    ui->comboBox_Exchange->addItem("郑州交易所");
    ui->comboBox_Exchange->addItem("大连交易所");
    ui->comboBox_Exchange->addItem("上海交易所");
    ui->comboBox_Exchange->addItem("金融交易所");
	ui->comboBox_Exchange->addItem("显示全部");

	ui->tableWidget_Contracts->setSelectionBehavior(QAbstractItemView::SelectRows);
	ui->tableWidget_Contracts->verticalHeader()->setVisible(false);
    ui->tableWidget_Contracts->setShowGrid(true);//显示表格线
    ui->tableWidget_Contracts->setSelectionMode ( QAbstractItemView::SingleSelection); //设置选择模式，选择单行
    ui->tableWidget_Contracts->setEditTriggers(QAbstractItemView::NoEditTriggers);//禁止编辑
    ui->tableWidget_Contracts->horizontalHeader()->setStretchLastSection(true);//该命令只是将最后一行的列宽度等于Table剩下的宽度

    ui->tableWidget_Selected->setSelectionBehavior(QAbstractItemView::SelectRows);
    ui->tableWidget_Selected->verticalHeader()->setVisible(false);
    ui->tableWidget_Selected->setShowGrid(true);//显示表格线
    ui->tableWidget_Selected->setSelectionMode ( QAbstractItemView::SingleSelection); //设置选择模式，选择单行
    ui->tableWidget_Selected->setEditTriggers(QAbstractItemView::NoEditTriggers);//禁止编辑
    ui->tableWidget_Selected->horizontalHeader()->setStretchLastSection(true);//该命令只是将最后一行的列宽度等于Table剩下的宽度

    connect(ui->comboBox_Exchange,SIGNAL(currentTextChanged(const QString &)),this,SLOT(UpdateExchange(const QString &)));
    //双击添加响应事件
    connect(ui->tableWidget_Contracts,SIGNAL(doubleClicked(QModelIndex)),this,SLOT(ButtonAddClicked(QModelIndex)));
    //双击删除响应事件
    connect(ui->tableWidget_Selected,SIGNAL(doubleClicked(QModelIndex)),this,SLOT(ButtonDelClicked(QModelIndex)));

	//上移按钮响应事件
    //connect(ui->Button_Up,SIGNAL(clicked()),this,SLOT(ButtonUpClicked()));
    //下移按钮响应事件
    //connect(ui->Button_Down,SIGNAL(clicked()),this,SLOT(ButtonDownClicked()));

    connect(this,SIGNAL(SigSubscribeMarketDataFailure()),this,SLOT(SlotSubscribeMarketDataFailure()));
    connect(ui->m_OK,SIGNAL(clicked()),this,SLOT(OKButtonClicked()));

    this->setFocusPolicy(Qt::StrongFocus);

    m_model = new QStandardItemModel(0, 1, this);
    m_completer = new QCompleter(m_model, this);
    ui->ContractName->setCompleter(m_completer);

    connect(m_completer, SIGNAL(activated(const QString&)), this, SLOT(onContractChoosed(const QString&)));
    connect(ui->ContractName, SIGNAL(textChanged(const QString&)), this, SLOT(onTextChanged(const QString&)));
}

void SelfMarketDialog::keyPressEvent(QKeyEvent *k){
	switch(k->key()){
	case Qt::Key_Return:
    case Qt::Key_Enter:{
            QString contract = ui->ContractName->text();
            QStringList list = contract.split("|");
            if(list.size() == 2){
                //判断该合约是否已被选择
                int iRowCnt = ui->tableWidget_Selected->rowCount();
                for(int i = 0; i < iRowCnt; i++){
                    QString strContractCodeSeclected = ui->tableWidget_Selected->item(i,0)->text();
                    if(list[0] == strContractCodeSeclected){
                        return;
                    }
                }
                //将选中的合约内容添加至已选合约列表中
                ui->tableWidget_Selected->insertRow(iRowCnt);
                ui->tableWidget_Selected->setItem(iRowCnt,0,new QTableWidgetItem(list[0]));
                ui->tableWidget_Selected->setItem(iRowCnt,1,new QTableWidgetItem(list[1]));
            }
        break;}
    default:
        break;
    }
}

SelfMarketDialog::~SelfMarketDialog()
{
    delete ui;
}

void SelfMarketDialog::SubscribeContractsChoosed(){
    //从配置文件中获取已订阅的自选合约
    QString contracts = UFXConfig::getInstance()->GetString("Default","contracts","");
    if(contracts != ""){
        QStringList list = contracts.split("|");
        QStringList lst;
        for (int i = 0; i < list.size(); i++){
            QStringList list2 = list[i].split(",");
            if(list2.size() == 2){
                lst << list2[0];
                //添加至已选合约列表
                ui->tableWidget_Selected->insertRow(0);
                ui->tableWidget_Selected->setItem(0,0,new QTableWidgetItem(list2[0]));
                ui->tableWidget_Selected->setItem(0,1,new QTableWidgetItem(list2[1]));
            }
        }
        //订阅行情
        g_CTPInterface->SubscribeMarketData(lst);
    }
}
void SelfMarketDialog::onContractChoosed(const QString& contract){
    ui->ContractName->clear();    // 清除已存在的文本更新内容
    ui->ContractName->setText(contract);
}

void SelfMarketDialog::onTextChanged(const QString& str)
{
    QStringList strlist;
    for (QMap<QString,QString>::iterator it = m_MapF1Contracts.begin();it != m_MapF1Contracts.end(); ++it ) {
            if(it.key().startsWith(str)){
                strlist<<it.key() +"|"+ it.value();
            }
    }
    for (QMap<QString,QString>::iterator it = m_MapF2Contracts.begin();it != m_MapF2Contracts.end(); ++it ) {
            if(it.key().startsWith(str)){
                strlist<<it.key() +"|"+ it.value();
            }
    }
    for (QMap<QString,QString>::iterator it = m_MapF3Contracts.begin();it != m_MapF3Contracts.end(); ++it ) {
            if(it.key().startsWith(str)){
                strlist<<it.key() +"|"+ it.value();
            }
    }
    for (QMap<QString,QString>::iterator it = m_MapF4Contracts.begin();it != m_MapF4Contracts.end(); ++it ) {
            if(it.key().startsWith(str)){
                strlist<<it.key() +"|"+ it.value();
            }
    }
    m_model->removeRows(0, m_model->rowCount());// 先清楚已经存在的数据，不然的话每次文本变更都会插入数据，最后出现重复数据
    for (int i = 0; i < strlist.size(); ++i)
    {
        m_model->insertRow(0);
        m_model->setData(m_model->index(0, 0), strlist.at(i));
    }
}

void SelfMarketDialog::showEvent(QShowEvent *){
	UpdateExchange(ui->comboBox_Exchange->currentText());
    ui->ContractName->clear();
}

void SelfMarketDialog::AddContractsInfo(CThostFtdcInstrumentField *pInstrument){
    QString contractCode    =  QString(pInstrument->InstrumentID);
    QString contractname    =  QString::fromLocal8Bit(pInstrument->InstrumentName);
    QString futu_exch_type  =  QString(pInstrument->ExchangeID);

    if(futu_exch_type == "CZCE"){
        m_MapF1Contracts.insert(contractCode,contractname);//郑州
    }else if(futu_exch_type == "DCE"){
        m_MapF2Contracts.insert(contractCode,contractname);//大连
    }else if (futu_exch_type == "SHFE"){
        m_MapF3Contracts.insert(contractCode,contractname);//上海
    }else if (futu_exch_type == "CFFEX"){
        m_MapF4Contracts.insert(contractCode,contractname);//金融
	}
}
void SelfMarketDialog::UpdateExchange(const QString & text){

	ui->tableWidget_Contracts->setRowCount(0);

    if(text == "郑州交易所" || text == "显示全部" ){
        int iRow = ui->tableWidget_Contracts->rowCount();
        for (QMap<QString,QString>::iterator it = m_MapF1Contracts.begin();it != m_MapF1Contracts.end(); ++it ) {
                ui->tableWidget_Contracts->insertRow(iRow); //插入新行
                ui->tableWidget_Contracts->setItem(iRow,0,new QTableWidgetItem(it.key()));
                ui->tableWidget_Contracts->setItem(iRow,1,new QTableWidgetItem(it.value()));
                iRow++;
        }
    }
	if (text == "大连交易所" || text == "显示全部" ){
        int iRow = ui->tableWidget_Contracts->rowCount();
        for (QMap<QString,QString>::iterator it = m_MapF2Contracts.begin();it != m_MapF2Contracts.end(); ++it ) {
                ui->tableWidget_Contracts->insertRow(iRow); //插入新行
                ui->tableWidget_Contracts->setItem(iRow,0,new QTableWidgetItem(it.key()));
                ui->tableWidget_Contracts->setItem(iRow,1,new QTableWidgetItem(it.value()));
                iRow++;
        }
    } 
    if (text == "上海交易所" || text == "显示全部" ){
        int iRow = ui->tableWidget_Contracts->rowCount();
        for (QMap<QString,QString>::iterator it = m_MapF3Contracts.begin();it != m_MapF3Contracts.end(); ++it ) {
                ui->tableWidget_Contracts->insertRow(iRow); //插入新行
                ui->tableWidget_Contracts->setItem(iRow,0,new QTableWidgetItem(it.key()));
                ui->tableWidget_Contracts->setItem(iRow,1,new QTableWidgetItem(it.value()));
                iRow++;
        }
    }
	if (text == "金融交易所" || text == "显示全部" ){
        int iRow = ui->tableWidget_Contracts->rowCount();
        for (QMap<QString,QString>::iterator it = m_MapF4Contracts.begin();it != m_MapF4Contracts.end(); ++it ) {
                ui->tableWidget_Contracts->insertRow(iRow); //插入新行
                ui->tableWidget_Contracts->setItem(iRow,0,new QTableWidgetItem(it.key()));
                ui->tableWidget_Contracts->setItem(iRow,1,new QTableWidgetItem(it.value()));
                iRow++;
        }
    }
    //根据内容调整列宽,给Table填充数据之后再调用该函数进行Resize
    //ui->tableWidget_Contracts->resizeColumnsToContents();
}
///确认按钮响应事件
void SelfMarketDialog::OKButtonClicked(){
    int rowcnt = ui->tableWidget_Selected->rowCount();

    if(0 == rowcnt){//判断已选合约中是否有选中的Item
        QMessageBox::warning(NULL,QString("WARNNING"),QStringLiteral("请输入有效合约代码!"));
        return;
    }else{
        QString contracts = "";
        for(int i =0; i < rowcnt;i++){
            QString strContractCode = ui->tableWidget_Selected->item(i,0)->text();
            QString strContractName = ui->tableWidget_Selected->item(i,1)->text();
            //订阅行情
            QStringList lst;
            lst<<strContractCode;
            g_CTPInterface->SubscribeMarketData(lst);

            if(i == 0){
                contracts = strContractCode+","+strContractName;
            }else{
                contracts  = contracts + "|"+ strContractCode+","+strContractName;
            }
        }
        //更新至配置文件
        UFXConfig::getInstance()->SetString("Default","contracts",contracts.toStdString().c_str());
    }
    emit destroyWin();
}

void SelfMarketDialog::SlotSubscribeMarketDataFailure(){
    QMessageBox::critical(this, QString("ERROR"), QString("行情订阅失败!"));
}

///添加响应事件
void SelfMarketDialog::ButtonAddClicked(const QModelIndex &index){
	QList<QTableWidgetItem *>  ItemsSelected  = ui->tableWidget_Contracts->selectedItems();
    if(0 == ItemsSelected.size() ){//判断是否有选中的Item
        QMessageBox::warning(NULL,QString("WARNNING"),QString("Please select a valid Item"));
    }else{
		//选中的行号
        int iRow = ItemsSelected.at(0)->row();
		//合约代码
        QString strContractCode = ui->tableWidget_Contracts->item(iRow,0)->text();
		//合约名称
        QString strContractName = ui->tableWidget_Contracts->item(iRow,1)->text();

        //判断该合约是否已被选择
        int iRowCnt = ui->tableWidget_Selected->rowCount();
        for(int i = 0; i < iRowCnt; i++){
            QString strContractCodeSeclected = ui->tableWidget_Selected->item(i,0)->text();
            if(strContractCode == strContractCodeSeclected){
                return;
            }
        }
        //将选中的合约内容添加至已选合约列表中
        ui->tableWidget_Selected->insertRow(iRowCnt);
        ui->tableWidget_Selected->setItem(iRowCnt,0,new QTableWidgetItem(strContractCode));
        ui->tableWidget_Selected->setItem(iRowCnt,1,new QTableWidgetItem(strContractName));
    }
}
///删除响应事件
void SelfMarketDialog::ButtonDelClicked(const QModelIndex &index){
    QList<QTableWidgetItem *>  ItemsSelected  = ui->tableWidget_Selected->selectedItems();
    if(0 == ItemsSelected.size() ){//判断已选合约中是否有选中的Item
        QMessageBox::warning(NULL,QString("WARNNING"),QString("Please select a valid Item"));
    }else{
        //选中的行号
        int iRow = ItemsSelected.at(0)->row();
        //删除选中的行
        ui->tableWidget_Selected->removeRow(iRow);
    }
}
///上移按钮响应事件
void SelfMarketDialog::ButtonUpClicked(){
    QList<QTableWidgetItem *>  ItemsSelected  = ui->tableWidget_Selected->selectedItems();
    if(0 == ItemsSelected.size() ){//判断已选合约中是否有选中的Item
        QMessageBox::warning(NULL,QString("WARNNING"),QString("Please select a valid Item"));
    }else{
        //选中的行号
        int iRow = ItemsSelected.at(0)->row();
        if(0 != iRow ){
            ///上一行内容
            //合约代码
            QString strContractCode = ui->tableWidget_Selected->item(iRow-1,0)->text();
            //合约名称
            QString strContractName = ui->tableWidget_Selected->item(iRow-1,1)->text();

            ///选中行的内容
            //合约代码
            QString strContractCodeSelected = ui->tableWidget_Selected->item(iRow,0)->text();
            //合约名称
            QString strContractNameSelected = ui->tableWidget_Selected->item(iRow,1)->text();

            ui->tableWidget_Selected->setItem(iRow -1 , 0 ,new QTableWidgetItem(strContractCodeSelected));
            ui->tableWidget_Selected->setItem(iRow -1 , 1 ,new QTableWidgetItem(strContractNameSelected));
            ui->tableWidget_Selected->setItem(iRow , 0 ,new QTableWidgetItem(strContractCode));
            ui->tableWidget_Selected->setItem(iRow , 1 ,new QTableWidgetItem(strContractName));
            ui->tableWidget_Selected->selectRow(iRow -1);
        }
    }
}
///下移按钮响应事件
void SelfMarketDialog::ButtonDownClicked(){
    QList<QTableWidgetItem *>  ItemsSelected  = ui->tableWidget_Selected->selectedItems();
    if(0 == ItemsSelected.size() ){//判断已选合约中是否有选中的Item
        QMessageBox::warning(NULL,QString("WARNNING"),QString("Please select a valid Item"));
    }else{
        //行数
        int iCnt = ui->tableWidget_Selected->rowCount();
        //选中的行号
        int iRow = ItemsSelected.at(0)->row();
        if(iCnt != iRow + 1  ){
            ///下一行内容
            //合约代码
            QString strContractCode = ui->tableWidget_Selected->item(iRow+1,0)->text();
            //合约名称
            QString strContractName = ui->tableWidget_Selected->item(iRow+1,1)->text();
            ///选中行的内容
            //合约代码
            QString strContractCodeSelected = ui->tableWidget_Selected->item(iRow,0)->text();
            //合约名称
            QString strContractNameSelected = ui->tableWidget_Selected->item(iRow,1)->text();

            ui->tableWidget_Selected->setItem(iRow +1 , 0 ,new QTableWidgetItem(strContractCodeSelected));
            ui->tableWidget_Selected->setItem(iRow +1 , 1 ,new QTableWidgetItem(strContractNameSelected));
            ui->tableWidget_Selected->setItem(iRow , 0 ,new QTableWidgetItem(strContractCode));
            ui->tableWidget_Selected->setItem(iRow , 1 ,new QTableWidgetItem(strContractName));
            ui->tableWidget_Selected->selectRow(iRow +1);
        }
    }
}
